<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Builder\FallbackBuilder;

/*总数字资源类型model*/

class ResourceType extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_type';

    /**
     * 获取数字资源大类列表
     * @param limit int 分页大小
     * @param is_play    是否发布   1 发布  2 撤销
     * @param keywords string 搜索关键词
     */
    public function lists($search_data = [])
    {
        $keywords = $search_data['keywords'] ?? '';
        $limit = !empty($search_data['limit']) ? $search_data['limit'] : 10;

        $res = $this->select('id', 'type_name', 'img', 'intro', 'create_time', 'number', 'is_show_new', 'is_show_read_list')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('type_name', 'like', "%$keywords%");
                }
            })->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 重置所有大类型的数量
     */
    public function resetResourceTypeNumber()
    {
        $res = $this->select('id')->where('is_del', 1)->get()->toArray();
        $resourceTotalModel = new ResourceTotal();
        foreach ($res as $val) {
            if ($val['id'] == 999) {
                $number = 1; //默认为1
            } else {
                $number = $resourceTotalModel->getResourceNum(null, $val['id']);
            }
            $this->where('id', $val['id'])->update(['number' => $number]);
        }
    }
}
